// pages/jiansuo/jiansuo.js
var word = {}
var radioo=''
//播放音乐组件
const myaudio = wx.createInnerAudioContext();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    show:false,
    content: "",
    pron: "",
    definition: "",
    audio:''
  },
  onLoad: function (options) {
    //初始化标题
    var title = options.title
    if (title) {
      wx.setNavigationBarTitle({
        title: title,
      })
    }

    //接收查看单词详情传入的详情 展示单词详情
    var contentWord=options.content;
    //判断如果查询的值不为空
    if(contentWord){
      //写入数据
      this.setData({
        content:contentWord
      })
      this.queryWord();
    }
  },
  /**
   * 用于当更新input组件中的值时同时更新对应变量的值
   */
  bindKeyInputContent: function (e) {
    this.setData({
      content: e.detail.value
    })
  },
  /**
   * 从本地词库检索单词
   */
  queryWord:function(){
    var that = this
    //调用云函数读取数据库数据 自定义分页函数
    wx.cloud.callFunction({
      name: 'GetWordList',
      data: {
        dbName: 'wordList',
        pageIndex: 1,//当前页数   
        pageSize: 1,//每页条数
        filter: {
          content:that.data.content
        }
      },
      success: res => {
        //将获取到的数据放在变量里
        var wordlist = res.result.data
        // console.log(wordlist)
        //判断云函数是否返回成功
        if (res.errMsg == "cloud.callFunction:ok") {
          //将取到的数据写入页面变量
          word = wordlist[0];
          this.setData({
            content: word.content,
            pron: word.pron,
            definition: word.definition,
            show: true
          });
        }
      }
    })
  },
  /**
   * 从网站API检索单词 
   * https://api.shanbay.com/bdc/search/?word=
   */
  search: function (e) {
    var that = this
    var content = that.data.content
    //调用请求接口方法
    wx.request({
      //地址
      url: 'https://api.shanbay.com/bdc/search/?word=' + content,
      //数据
      data: {},
      //请求方式
      method: 'GET',
      //成功返回值
      success: function (res) {
        var msg = res.data.msg
        //如果获取到结果
        if (msg == "SUCCESS") {
          //将数据写入页面
          that.setData({
            //单词
            content: res.data.data.content,
            //读音链接
            audio: res.data.data.audio_addresses.us[0],
            //音标
            pron: res.data.data.pron,
            //释义
            definition: res.data.data.definition,
            show: true
          })
          radioo = res.data.data.audio;

        } else {
          //查询不到 提示
          wx.showModal({
            title: '提示',
            content: '对不起，查询不到该词信息',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                console.log('用户点击确定')
              }
            }
          })
        }

      },
      fail: function () {
      },
      complete: function () {
      }
    })
  },
  /**
   * 读英语
   */
  read: function () {
    myaudio.src=radioo
    myaudio.play();
    // console.log(myaudio.duration);
  }
})